/* Copyright (c) 2016-2020 Enfry Ltd. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Enfry. 
 * You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with Enfry.
 */
package com.enfry.storage.common;

import java.util.regex.Pattern;

import org.im4java.core.ConvertCmd;
import org.im4java.core.IMOperation;

import com.enfry.storage.exception.ExCode;
import com.enfry.storage.exception.StorageException;

/**
 * 图片工具
 * @Title com.enfry.storage.util.IMGUtils
 * @author liulei
 * @date 2016年7月25日
 */
public class IMGUtils {
    // 缩略图百分比匹配
    private static Pattern percentPattern = Pattern.compile("^\\d+$");

    public static void zoom(String raw, String path) {
        zoom(raw, path, path);
    }

    public static void zoom(String raw, String srcPath, String newPath) {
        IMOperation op = new IMOperation();
        ConvertCmd cmd = new ConvertCmd(true);
        op.addImage();
        if(percentPattern.matcher(raw).matches()){
            raw = raw+"%"+raw+"%"; //按像素百分比
        }else{
            raw = raw+"^"; //按像素
        }
        op.addRawArgs("-sample", raw);
        op.addRawArgs("-gravity", "center");
        op.addRawArgs("-quality", "100");
        op.addImage();

        try {
            cmd.run(op, srcPath, newPath);
        } catch (Exception e) {
            throw new StorageException(ExCode.IMG_ZOOM_ERR);
        }
    }

}
